package cn.moon.client.handler;

import cn.moon.client.channel.ClientChannelManager;
import cn.moon.protocol.ProxyMessage;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.bytes.ByteArrayDecoder;
import io.netty.handler.codec.bytes.ByteArrayEncoder;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.TimeUnit;

/**
 * 客户端处理器
 * 负责与服务端通信
 */
@Slf4j
public class ClientHandler extends SimpleChannelInboundHandler<ProxyMessage> {

    private static final int RECONNECT_DELAY = 10;

    private final NioEventLoopGroup workerGroup = new NioEventLoopGroup();

    private final Bootstrap clientBootstrap;
    private final String bridgeHost;
    private final int bridgePort;
    private final int localPort;

    public ClientHandler(Bootstrap clientBootstrap, String bridgeHost, int bridgePort, int localPort){
        this.clientBootstrap = clientBootstrap;
        this.bridgeHost = bridgeHost;
        this.bridgePort = bridgePort;
        this.localPort = localPort;

    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, ProxyMessage proxyMessage) {

        log.debug("======== ClientHandler 收到消息向内部转发 ========");

        Bootstrap bootstrap = new Bootstrap();

        bootstrap.group(workerGroup)
                .channel(NioSocketChannel.class)
                .option(ChannelOption.AUTO_READ, true)
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    public void initChannel(SocketChannel ch) {
                        ch.pipeline().addLast(new ByteArrayDecoder());
                        ch.pipeline().addLast(new ByteArrayEncoder());
                        ch.pipeline().addLast(new LocalHandler(proxyMessage.getChannelId()));
                    }
                });

        bootstrap.connect("localhost", localPort).addListener((ChannelFutureListener) future -> {

            if (future.isSuccess()) {
                future.channel().writeAndFlush(proxyMessage.getData());
            }else {
                log.error("===== 连接本地服务出错 ====");
            }

        });


    }

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) {
        if (!(evt instanceof IdleStateEvent)) {
            return;
        }

        IdleStateEvent e = (IdleStateEvent) evt;

        if (e.state() == IdleState.READER_IDLE) {
            // The connection was OK but there was no traffic for last period.
            ctx.close();
        }

    }


    @Override
    public void channelUnregistered(final ChannelHandlerContext ctx) throws Exception {

        ctx.channel().eventLoop().schedule(() -> {

            clientBootstrap.connect(bridgeHost, bridgePort)
                    .addListener((ChannelFutureListener) future -> {

                        if (future.isSuccess()) {

                            Channel channel = future.channel();

                            ClientChannelManager.setClientChannel(channel);

                            ProxyMessage proxyMessage = new ProxyMessage();

                            proxyMessage.setType(ProxyMessage.CONNECT);

                            channel.writeAndFlush(proxyMessage);

                            log.info("======== 连接(重连)成功 ========");
                        }

                    });
        }, RECONNECT_DELAY, TimeUnit.SECONDS);
    }

}
